﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Migrations.Model;
using System.Data.SQLite;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCOChart
{
    public partial class FormTableSql:Form
    {
        public DataTable _ds;
        private LogHelper _logHelper;

        public FormTableSql()
        {
            InitializeComponent();
            this.Text = "AntdUI Table";
            
            init();
            UpdateTableData();
        }

        public void init()
        {
            _logHelper = new LogHelper(this.richTextBox1);
            _logHelper.Log("程序启动");

            // 创建数据库
            SQLiteHelper.CreateDBFile("User.db");
            // 创建表
            string createTableSql = @"
                                    CREATE TABLE IF NOT EXISTS User (
                                        ID INTEGER PRIMARY KEY,
                                        Name TEXT NOT NULL,
                                        Age INTEGER,
                                        Job TEXT
                                    )";
            if (!SQLiteHelper.CreateTable("User.db", createTableSql))
            {
                MessageBox.Show("创建失败");
            }

            // 动态添加方式初始化
            //var columns = new AntdUI.ColumnCollection();
            //columns.Add(new AntdUI.Column("Seq", "序号").SetFixed().SetLocalizationTitleID("Table.Column."));
            // 初始化ui table
            table1.Columns = new AntdUI.ColumnCollection
            {
                new AntdUI.ColumnCheck("check"),
                new AntdUI.Column("Seq", "序号").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Name", "姓名").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Age", "年龄", AntdUI.ColumnAlign.Center).SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Job", "工作", AntdUI.ColumnAlign.Center).SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Btn", "操作1").SetFixed().SetWidth("auto").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Select", "下拉框").SetFixed().SetWidth("auto").SetLocalizationTitleID("Table.Column."),
            };
            table1.EditMode = AntdUI.TEditMode.DoubleClick;
            
            pagination1.PageSizeOptions = new int[] { 10, 20, 30, 50, 100 };

            // table 属性设置
            table1.Bordered = true;  // 显示边框
            table1.EnableHeaderResizing = true;  // 手动调整列宽度
            table1.Columns["Age"].SortOrder = true;

            _logHelper.Log("初始化完成", LogLevel.Error);
        }

        /// <summary>
        /// 显示表数据
        /// </summary>
        public void UpdateTableData()
        {
            string strSql = "select * from User";
            _ds = SQLiteHelper.SqlTable("User.db", strSql);

            // 初始化分页控件
            pagination1.Total = _ds.Rows.Count; // 设置总条数
            pagination1.Current = 0;
            //pagination1..PageTotal = (int)Math.Ceiling((double)_ds.Rows.Count / pagination1.PageSize);
            table1.DataSource = GetPageData(_ds, 1, pagination1.PageSize);

            _logHelper.Log("数据更新");
        }

        private void button_add_Click(object sender, EventArgs e)
        {
            string name = input_name.Text;
            int.TryParse(input_age.Text, out int age);
            string job = input_job.Text;

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(job) || age == 0)
            {
                MessageBox.Show("数据输入不全");
                _logHelper.Log("数据输入不全");
                return;
            }
            string sql = $"insert into User (Name, Age, Job) values('{name}', '{age}', '{job}')";
            if (SQLiteHelper.ExecuteNonQuery("User.db", sql) != 1)
            {
                MessageBox.Show("插入失败");
                _logHelper.Log("插入失败");
            }
            input_name.Clear();
            input_age.Clear();
            input_job.Clear();
            _logHelper.Log("数据插入成功");

            UpdateTableData();
        }

        #region 分页
        /// <summary>
        /// 获取分页数据显示
        /// </summary>
        /// <param name="current"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        object GetPageData(DataTable ds, int currentPage, int pageSize)
        {
            var list = new List<TestClass>();
            //int start = Math.Abs(currentPage - 1) * pageSize;

            int startRow = (currentPage - 1) * pageSize;
            int endRow = Math.Min(startRow + pageSize, ds.Rows.Count);

            for (int i = startRow; i < endRow; i++)
            {
                // 将每一行数据映射到 TestClass 对象
                var testClass = new TestClass(i+1, ds.Rows[i]);

                // 将对象添加到列表
                list.Add(testClass);
            }

            return list;
        }

        private string pagination1_ShowTotalChanged(object sender, AntdUI.PagePageEventArgs e)
        {
            return $"{e.PageSize} / {e.Total}条 {e.PageTotal}页";
        }

        private void pagination1_ValueChanged(object sender, AntdUI.PagePageEventArgs e)
        {
            int currentPage = e.Current;
            int pageSize = e.PageSize;
            table1.DataSource = GetPageData(_ds, currentPage, pageSize);
        }
        #endregion


        #region 更新数据
        private void UpdateToDatabase(TestClass row)
        {
            try
            {
                // 构建更新 SQL 语句
                string sql = $"update User " +
                            $"set Name = '{row.Name}', Age = '{row.Age}', Job = '{row.Job}'" +
                            $" where ID='{row.ID}'";
                if (SQLiteHelper.ExecuteNonQuery("User.db", sql) == 1)
                {
                    MessageBox.Show("修改成功");
                    _logHelper.Log("数据修改成功");
                }
                else
                {
                    MessageBox.Show("修改失败");
                    _logHelper.Log("数据修改失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败：" + ex.Message);
            }
        }
        /// <summary>
        /// 双击表格更新内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool table1_CellEndEdit(object sender, AntdUI.TableEndEditEventArgs e)
        {
            var newVal = e.Value;
            var row = e.RowIndex - 1; // 当前行数据
            var column = e.ColumnIndex; // 当前列

            var dataSource = table1.DataSource as List<TestClass>;
            if (dataSource == null)
            {
                MessageBox.Show("数据源无效！");
                return false;
            }
            var rowData = dataSource[row];
            var columnName = table1.Columns[column].Key;
            switch (columnName)
            {
                case "Name":
                    rowData.Name = newVal.ToString();
                    break;
                case "Age":
                    rowData.Age = Convert.ToInt32(newVal);
                    break;
                case "Job":
                    rowData.Job = newVal.ToString();
                    break;
                default:
                    MessageBox.Show("无效的列名！");
                    return false;
            }
            DialogResult result = MessageBox.Show("是否更新数据？", "数据更新", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                // 保存到数据库
                UpdateToDatabase(rowData);

                // 刷新表格
                table1.DataSource = null; // 清空数据源
                table1.DataSource = dataSource; // 重新绑定数据源
                _logHelper.Log("数据更新成功");
                // 返回 true 表示更新成功
                return true;
            }
            else
            {
                // 返回 false 表示取消更新
                return false;
            }
        }


        #endregion

        #region 删除数据
        private void table1_CellButtonClick(object sender, AntdUI.TableButtonEventArgs e)
        {
            if (e.Record is TestClass data)
            {
                if (e.Btn.Id == "delete")
                {
                    if (AntdUI.Modal.open(new AntdUI.Modal.Config(this, "是否删除", new AntdUI.Modal.TextLine[] {
                    new AntdUI.Modal.TextLine(data.Name,AntdUI.Style.Db.Primary),
                    new AntdUI.Modal.TextLine(data.Job,6,AntdUI.Style.Db.TextSecondary)
                    }, AntdUI.TType.Error)
                    {
                        CancelText = null,
                        OkType = AntdUI.TTypeMini.Error,
                        OkText = "删除"
                    }) == DialogResult.OK)
                    {
                        table1.Spin("正在删除中...", config =>    // spin进度条
                        {
                            DeleteDatabase(data.ID);
                        }, () =>
                        {
                            System.Diagnostics.Debug.WriteLine("删除成功");
                            _logHelper.Log($"数据{data.Name}删除成功");
                            UpdateTableData();
                        });
                    }
                }
            }
        }
        public void DeleteDatabase(int id)
        {
            string sql = $"DELETE FROM User where ID='{id}'";
            if (SQLiteHelper.ExecuteNonQuery("User.db", sql) != 1)
            {
                MessageBox.Show("删除失败");
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            FormPort port = new FormPort();
            port.Show();
        }

        private void button_MESOpen_Click(object sender, EventArgs e)
        {
            FormMesOpen formMesOpen = new FormMesOpen();
            formMesOpen.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FormMachineMES formMachineMES = new FormMachineMES();
            formMachineMES.Show();
        }
    }

    public class TestClass : AntdUI.NotifyProperty
    {
        public TestClass(int index, DataRow row)
        {
            Seq = index;
            ID = Convert.ToInt32(row["ID"]);
            _name = row["Name"].ToString();
            _age = Convert.ToInt32(row["Age"]);
            _job = row["Job"].ToString();
            _btn = new AntdUI.CellButton("delete", "Delete", AntdUI.TTypeMini.Error);
            AntdUI.Select select = new AntdUI.Select();
            select.Items.AddRange(new AntdUI.SelectItem[] {
                new AntdUI.SelectItem("two"){ Sub=new List<object>{ "five menu item", "six six six menu item"} },
            });
            _btn_select = new AntdUI.CellLink[] {
                        new AntdUI.CellButton("b2") { ShowArrow = true },
                    };
        }
        public TestClass() { }

        public int Seq {  get; set; }  // 序号自增

        public int ID { get; set; }

        bool _check = false;
        public bool check
        {
            get => _check;
            set
            {
                if (_check == value) return;
                _check = value;
                OnPropertyChanged();
            }
        }

        string _name;
        public string Name
        {
            get => _name;
            set
            {
                if (_name == value) return;
                _name = value;
                OnPropertyChanged();
            }
        }

        int _age;
        public int Age
        {
            get => _age;
            set
            {
                if (_age == value) return;
                _age = value;
                OnPropertyChanged();
            }
        }

        string _job;
        public string Job
        {
            get => _job;
            set
            {
                if (_job == value) return;
                _job = value;
                OnPropertyChanged();
            }
        }

        AntdUI.CellButton _btn;
        public AntdUI.CellButton Btn
        {
            get => _btn;
            set
            {
                _btn = value;
                OnPropertyChanged();
            }
        }

        AntdUI.CellLink[] _btn_select;
        public AntdUI.CellLink[] Select
        {
            get => _btn_select;
            set
            {
                _btn_select = value;
                OnPropertyChanged();
            }
        }
    }
}
